<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>使用代理工厂完成自定义验证组件</title>
    <style>
        .error{
            border: 2px solid red;
        }
    </style>
</head>
<body>
    <input type="text" validate rule="max:12,min:2">
    <input type="text" validate rule="max:8,isNum">
    <script>
        'use strict'
        class Conform{
            max(value,length){
                return value.length < length;
            }
            min(value,length){
                return value.length > length;
            }
            isNum(value){
                let zz = /^\d+$/;
                return zz.test(value);
            }
        }

        // let a = new Conform();
        // console.log(a.max("uiyhui",8));
        // console.log(a.isNum("4534"));

        function proxyFactory(prama) {
            return new Proxy(prama,{
                // 第一个参数是传入的数组，第二个参数是数组传入的键名，第三个参数是对应传入的键值
                set(array,key,el){
                    const rule = el.getAttribute('rule');
                    const rules = rule.split(",");
                    const conform = new Conform();
                    let state = rules.every(item => {
                        const info = item.split(":");
                        return conform[info[0]](el.value,info[1]);
                    });
                    el.classList[state ? "remove" : "add"] ("error");
                    return true;
                },
                get(array,key){
                    return array[key];
                }
            })
        }

        let proxy = proxyFactory(document.querySelectorAll('[validate]'));
        proxy.forEach((item,idx) => {
            item.addEventListener('keyup',function () {
                proxy[idx] = this;
            })
        });
    </script>
</body>
</html>